package com.luzhikun.aSynchronouseListener_1;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;

/*
 * @Author liu-miss
 * @Description Servlet线程异步+监听器
 * @Date 20:10 2021/5/6
 * @Param
 * @return
 **/
@WebServlet(name = "SynchronouseServlet", value = "/SynchronouseServlet",asyncSupported = true)
public class SynchronouseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置字符集
        response.setContentType("text/html;charset=UTF-8");
        // 创建输出流
        PrintWriter writer = response.getWriter();
        writer.println("主线程开始");

        // 获取异步上下文对象
            AsyncContext as = request.startAsync();
        // 创建子线程
        SunRunnable sr=new SunRunnable(as);
        // 设置响应时间(如果不设置，页面会自动等待30秒然后完成，个人建议 必须设置)
        as.setTimeout(1000);
        as.addListener(new AsyncListener() {
            @Override
            public void onComplete(AsyncEvent asyncEvent) throws IOException {
                System.out.println("异步操作已完成");
            }

            @Override
            public void onTimeout(AsyncEvent asyncEvent) throws IOException {
                System.out.println("异步操作已超时");
            }

            @Override
            public void onError(AsyncEvent asyncEvent) throws IOException {

            }

            @Override
            public void onStartAsync(AsyncEvent asyncEvent) throws IOException {

            }
        });



        // 开启子线程
        as.start(sr);

        // 向浏览器输出
        writer.println("主线程结束<br>");
        writer.println("请查看邮件<a href='show.jsp'>邮件</a>");


    }

}
